<template>
    <div>
         <div class="init-file-p">
                   
            <el-button @click="selectFile" type="primary" icon='el-icon-plus'>导入Excel</el-button>
            
            <input ref="fileInput" @change="fileChange" type="file" multiple style="display:none;">
        </div>
        <div class="init-file-p">
                    
                    <div v-show="fileList.length > 0" class="sel-file-name">
                        <div class="file-tag">选择的文件：</div>
                        <el-tag class="file-tag"
                            :key="tag.id"
                            v-for="tag in fileList"
                            closable
                           
                            @close="removeFile(tag)">
                             {{tag.name}}
                        </el-tag>
                    </div>
                    <div v-show="wrongList.length == 0 && fileList.length > 0">
                     
                      <el-alert  class="el-alert"
                            :title="list.length + '条数据检测通过，格式正确满足导入要求'"
                            type="success"
                            :closable="false"
                            show-icon>
                        </el-alert>
                        <el-button @click="toLook()" type="success" icon='el-icon-search'>查看数据</el-button>
                        <el-button @click="submit" type="success" icon='el-icon-check'>提交数据</el-button>
                    </div>
                    <div v-show="wrongList.length > 0">
                        <el-alert  class="el-alert"
                            :title="'错误共计' + wrongList.length + '条，请校正后重新选择文件导或在线修改'"
                            type="error"
                            :closable="false"
                            show-icon>
                        </el-alert>
                        <el-button  @click="toModify()" type="danger" icon='el-icon-edit'>在线修改</el-button>
                    </div>
                </div>
             
                <div class="pro-div" v-show="100 > progress && progress > 0">
                    <el-progress :text-inside="true" :stroke-width="26" :percentage="progress" status="success"></el-progress>
                </div>

                  <modify :visible='visible' :action='action' :data="list" :map="map"
                    @close='visible = false'
                    @delete="deleteById"
                    @confirm='modifyConfirm'
                 ></modify>
    </div>
</template>
<script>
 /* eslint-disable */
import modify from './modify'
import loading from './loading'


export default {
    components: {
        modify, loading
    },
     computed: {
        schoolId () {
            return this.$store.state.common.cookiesObj.schoolId
        },
        wrongList () {
            var list = []
            for (var item of this.list) {
                var flag = true
                for (var key in item) {
                    if (!item[key].legal && typeof item[key] == 'object') {
                        flag = false
                    }
                }
                if (!flag) {
                    list.push(item)
                }
            }
            return list
      }
    },

    props: {
        map: Object,
        xlsxMap: Object
    },
    
    data () {
        return {
            visible: false,
            loadingVisible: false,
            progress: 0,
            isOver: false,

            errList: [], 

            fileList: localStorage.fileList ? JSON.parse(localStorage.fileList) : [],
            list: localStorage.list ? JSON.parse(localStorage.list) : [],
            action: ''
        }
    },
    methods: {
        selectFile () {
            this.$refs.fileInput.click()
            console.log(this.xlsxMap)
            console.log(this.map)
        },
       
        async fileChange (e) {
            var fileList = e.target.files
           
            for (let i = 0; i < fileList.length; i++) {
                var file = fileList[i]
                var name = file.name
                var suffix = name.substring(name.lastIndexOf('.')).toUpperCase()
                if (suffix == '.XLSX') {
                    var id = this.xlsxMap.uuid()
                  
                    this.pushFile({name, id})
                    await this.readXlsx({file, fileId: id})
                } else {
                    this.$message.error('“' + name + '” 文件有误，请上传.xlsx文件')
                }
            }
            this.$refs.fileInput.value = ''
        },

        pushFile (obj) {
          this.fileList.push(obj)
          localStorage.fileList = JSON.stringify(this.fileList)
        },

        pushList (list) {
          this.list = this.list.concat(list)
          localStorage.list = JSON.stringify(this.list)
        },

        deleteById (id) {
            for (var i = 0; i < this.list.length; i++) {
                if (this.list[i].id == id) {
                    this.list.splice(i, 1)
                }
            }
          localStorage.list = JSON.stringify(this.list)
        },

        readXlsx ({file, fileId}) {
            return new Promise((resolve, reject) => {
              this.xlsxMap.readData({file, fileId, check: true, map: this.map}).then(list => {
                    if (list.length > 0) {
                        this.pushList(list)
                    }
                    resolve()
              })
            })
        },

        toModify (type) {
            this.action = 'modify'
            this.visible = true
        },
        toLook (type) {
            this.action = 'look'
            this.visible = true
        },
        removeFile (file) {
            for (let i = this.fileList.length - 1; i >= 0; i--) {
              let temp = this.fileList[i]
              if (temp.id == file.id) {
                this.fileList.splice(i, 1)
              }
            }
            localStorage.fileList = JSON.stringify(this.fileList)

            for (let i = this.list.length - 1; i >= 0; i--) {
              let temp = this.list[i]
              if (temp.fileId == file.id) {
                this.list.splice(i, 1)
              }
            }
            localStorage.list = JSON.stringify(this.list)
        },
        clearFile () {
            for (let file of this.fileList) {
                this.removeFile(file)
            }
        },
        modifyConfirm (list) {
            for (var i = 0; i < this.list.length; i++) {
              var item = this.list[i]
              for (var n = 0; n < list.length; n++) {
                  var obj = list[n]
                  if (item.id == obj.id) {
                     this.list.splice(i, 1, obj)
                  }
              }
          }
        
          this.list = this.xlsxMap.checkList({list: this.list, map: this.map})
          localStorage.list = JSON.stringify(this.list)
        },

        isRight () {
            if (this.wrongList.length == 0) {
                return true
            } else {
                return false
            }
        },

        submit(){
            this.$emit('submit', this.getData())
        },

        complete(){
            this.isOver = true
            this.progress = 100
            this.clearFile()
        },

        handleError (list) {
          for (var item of list) {
            var col = ''
            for (var key in item) {
                if (key != 'errormsg') {
                   col = key.replace(key[0], key[0].toLowerCase())
                   item[col] = item[key]
                }
            }
          
            for (var i = 0; i < this.list.length; i++) {
              var t = this.list[i]
              if (t[col].val == item[col]) {
                  t[col].legal = false
                  t[col].errVal = item[col]
                  t[col].errDesc = item.errormsg
                  this.list.splice(i, 1, t)
              }
            }
          }
          
          localStorage.list = JSON.stringify(this.list)
        },
       
         getData () {
            var list = JSON.parse(JSON.stringify(this.list))
            
            var data = []
            for (var item of list) {
                delete item.id
                delete item.fileId
                var obj = {}
                for (var key in item) {
                    obj[key] = item[key].val
                }
                data.push(obj)
            }
            return data
        },
        setGradeList (list) {
            this.xlsxMap.gradeList = list
        },
        setPeroidsList(list){
            this.xlsxMap.peroidsList = list
        }
    }
}
</script>
<style scoped>

.middle{display: inline-block;vertical-align: middle;}
/* .init-file-p{padding:0 0 15px 0;} */
.sel-file-name{display: inline-block;vertical-align: middle;padding: 0 30px 0 0px;}
.el-alert{margin: 20px 0;}

.file-tag{display: inline-block;vertical-align: middle;margin: 10px;}
</style>
